#include "SeqList.h"

void SLInit(SL* ps)
{
	ps->arr = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

void SLDestory(SL* ps)
{
	if (ps->arr) {
		free(ps->arr);
	}
	ps->arr = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

void SLPrint(const SL* const ps) {
	assert(ps != NULL);
	for (int i = 0; i < ps->size; ++i) {
		printf("%d ", ps->arr[i]);
	}
	printf("\n");
}

void SLCheckCapacity(SL* ps)
{
	while (ps->size >= ps->capacity) {
		int newCapacity = (ps->capacity == 0 ? 4 : 2 * ps->capacity);
		SLDataType* tmp = (SLDataType*)realloc(ps->arr, newCapacity * sizeof(SLDataType));
		if (tmp == NULL) {
			perror("realloc error"); exit(1);
		}
		else {
			ps->arr = tmp;
			ps->capacity = newCapacity;
			tmp = NULL;
		}
	}
}

void SLPushBack(SL* ps, SLDataType x)
{
	assert(ps != NULL);
	SLCheckCapacity(ps);
	ps->arr[ps->size++] = x;
}

void SLPushFront(SL* ps, SLDataType x)
{
	assert(ps != NULL);
	SLCheckCapacity(ps);
	for (int i = ps->size; i > 0; --i) {
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[0] = x;
	++ps->size;
}

void SLPopBack(SL* ps)
{
	assert(ps != NULL);
	assert(ps->size > 0);
	--ps->size;
}

void SLPopFront(SL* ps)
{
	assert(ps != NULL);
	assert(ps->size > 0);
	for (int i = 0; i < ps->size - 1; ++i) {
		ps->arr[i] = ps->arr[i + 1];
	}
	--ps->size;
}

void SLInsert(SL* ps, const int pos, SLDataType x)
{
	assert(ps != NULL);
	assert(pos >= 0 && pos <= ps->size);
	SLCheckCapacity(ps);
	for (int i = ps->size; i > pos; --i) {
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[pos] = x;
	++ps->size;
}

void SLErase(SL* ps, const int pos)
{
	assert(ps != NULL);
	assert(pos >= 0 && pos < ps->size);
	for (int i = pos; i < ps->size - 1; ++i) {
		ps->arr[i] = ps->arr[i + 1];
	}
	--ps->size;
}

int SLFind(SL* ps, SLDataType x)
{
	assert(ps != NULL);
	for (int i = 0; i < ps->size; ++i) {
		if (ps->arr[i] == x)
			return i;
	}
	return -1;
}

